/**
 * 医院建筑数据操作API
 * 基于IndexedDB的医院建筑管理功能
 */

import { hospitalDB, HospitalBuildingData } from '../indexedDB'

export interface CreateHospitalBuildingRequest {
  name: string
  description: string
  hospitalId: string
  center: [number, number]
  bounds: {
    north: number
    south: number
    east: number
    west: number
  }
  modelPath: string
  floors?: string[]
  metadata?: Record<string, any>
}

export interface UpdateHospitalBuildingRequest extends Partial<CreateHospitalBuildingRequest> {
  id: string
}

export interface HospitalBuildingResponse {
  success: boolean
  msg: string
  data?: HospitalBuildingData
}

export interface HospitalBuildingsListResponse {
  success: boolean
  msg: string
  data?: HospitalBuildingData[]
}

/**
 * 创建医院建筑
 */
export const createHospitalBuilding = async (
  building: CreateHospitalBuildingRequest
): Promise<HospitalBuildingResponse> => {
  try {
    const data = await hospitalDB.addHospitalBuilding({
      ...building,
      floors: building.floors || [],
      metadata: building.metadata || {}
    })
    
    return {
      success: true,
      msg: '医院建筑创建成功',
      data
    }
  } catch (error) {
    console.error('创建医院建筑失败:', error)
    return {
      success: false,
      msg: '创建医院建筑失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 获取所有景区列表
 */
export const getAttractionsList = async (): Promise<AttractionsListResponse> => {
  try {
    // 暂时使用示例数据，实际项目中应该从数据库加载
    const data = [
      {
        id: 'attraction_1',
        name: '西湖风景区',
        description: '杭州著名景区，历史文化底蕴深厚',
        center: [120.1551, 30.2741] as [number, number],
        bounds: {
          north: 30.2791,
          south: 30.2691,
          east: 120.1601,
          west: 120.1501
        },
        modelPath: '/models/xihu_attraction.glb',
        metadata: {
          type: '文化景区',
          level: 'AAAAA',
          openTime: '6:00-22:00',
          ticketPrice: '免费'
        },
        createdAt: new Date('2023-01-01'),
        updatedAt: new Date()
      },
      {
        id: 'attraction_2',
        name: '雷峰塔景区',
        description: '著名古塔景区，有深厚的历史文化内涵',
        center: [120.1495, 30.2313] as [number, number],
        bounds: {
          north: 30.2363,
          south: 30.2263,
          east: 120.1545,
          west: 120.1445
        },
        modelPath: '/models/leifeng_tower.glb',
        metadata: {
          type: '古建景区',
          level: 'AAAA',
          openTime: '8:00-17:30',
          ticketPrice: '40元'
        },
        createdAt: new Date('2023-01-01'),
        updatedAt: new Date()
      },
      {
        id: 'attraction_3',
        name: '湖滨商业区',
        description: '集购物、餐饮、娱乐于一体的商业景区',
        center: [120.1606, 30.2594] as [number, number],
        bounds: {
          north: 30.2644,
          south: 30.2544,
          east: 120.1656,
          west: 120.1556
        },
        modelPath: '/models/hubin_commercial.glb',
        metadata: {
          type: '商业景区',
          level: 'AAA',
          openTime: '9:00-22:00',
          ticketPrice: '免费'
        },
        createdAt: new Date('2023-01-01'),
        updatedAt: new Date()
      }
    ]
    
    return {
      success: true,
      msg: '获取景区列表成功',
      data
    }
  } catch (error) {
    console.error('获取景区列表失败:', error)
    return {
      success: false,
      msg: '获取景区列表失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 根据ID获取景区详情
 */
export const getAttractionById = async (id: string): Promise<AttractionResponse> => {
  try {
    const data = await hospitalDB.getAttraction(id)
    if (!data) {
      return {
        success: false,
        msg: '景区不存在'
      }
    }
    
    return {
      success: true,
      msg: '获取景区详情成功',
      data
    }
  } catch (error) {
    console.error('获取景区详情失败:', error)
    return {
      success: false,
      msg: '获取景区详情失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 更新景区信息
 */
export const updateAttraction = async (
  attraction: UpdateAttractionRequest
): Promise<AttractionResponse> => {
  try {
    // 先获取现有数据
    const existing = await hospitalDB.getAttraction(attraction.id)
    if (!existing) {
      return {
        success: false,
        msg: '景区不存在'
      }
    }
    
    // 合并更新数据
    const updatedData: AttractionData = {
      ...existing,
      ...attraction,
      updatedAt: new Date()
    }
    
    await hospitalDB.updateAttraction(updatedData)
    
    return {
      success: true,
      msg: '景区更新成功',
      data: updatedData
    }
  } catch (error) {
    console.error('更新景区失败:', error)
    return {
      success: false,
      msg: '更新景区失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 删除景区
 */
export const deleteAttraction = async (id: string): Promise<AttractionResponse> => {
  try {
    // 检查景区是否存在
    const existing = await hospitalDB.getAttraction(id)
    if (!existing) {
      return {
        success: false,
        msg: '景区不存在'
      }
    }
    
    await hospitalDB.deleteAttraction(id)
    
    return {
      success: true,
      msg: '景区删除成功'
    }
  } catch (error) {
    console.error('删除景区失败:', error)
    return {
      success: false,
      msg: '删除景区失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 预设景区模型选项
 */
export const getPresetModels = () => {
  return [
    {
      label: '现代购物中心',
      value: '/models/shopping_mall.glb',
      description: '多层现代购物中心建筑群'
    },
    {
      label: '传统园林',
      value: '/models/traditional_garden.glb',
      description: '中式传统园林景观'
    },
    {
      label: '主题公园',
      value: '/models/theme_park.glb',
      description: '大型主题游乐园'
    },
    {
      label: '度假酒店',
      value: '/models/resort_hotel.glb',
      description: '度假酒店建筑群'
    },
    {
      label: '文化博物馆',
      value: '/models/museum.glb',
      description: '文化展览馆建筑'
    }
  ]
}

/**
 * 预设楼层选项
 */
export const getPresetFloors = () => {
  return [
    'B2', 'B1', 'L1', 'L2', 'L3', 'L4', 'L5'
  ]
}